import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { useUserStoreHook } from '@/store/modules/user';
import { VITE_APP_BASE_API as baseUrl } from '@/utils/base'

// 创建 axios 实例
const service = axios.create({
  baseURL: baseUrl,
  timeout: 50000,
  // headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// location ^~ /api { 
//   proxy_pass              http://172.20.4.190:8880/api; 
//   proxy_set_header        X-Forwarded-Proto \$scheme;
//   proxy_set_header        X-Real-IP \$remote_addr;
//   proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;
// }
// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code } = response.data;
    const message = response.data.message && response.data.msg
    // console.log("successmessage -------->",response)
    if (code === '000000') {
      return response.data;
    }
    if (code === 700002) {
      ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        localStorage.clear();
        window.location.href = '/';
      });
      return false;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    ElMessage.error(message || '系统出错');
    return Promise.reject(new Error(message || 'Error'));
  },
  (error: any) => {
    if (error.response.data) {
      console.log("errormessage -------->", error.response)
      const { code, message } = error.response.data;
      if (code === 700002) {
        ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          localStorage.clear();
          window.location.href = '/';
        });
      } else {
        ElMessage.error(message || '系统出错');
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
